﻿#include "ratecontrol.h"

RateControl::RateControl()
{
    m_sampling = 0;
    m_allowErrorCode = 0;
}

RateControl::RateControl(int sampling)
{
    setSampling(sampling);
}

void RateControl::setAlowErrorCount(int allowDataSize)
{
    m_allowErrorCode = allowDataSize;
}

int RateControl::allowErrorCount()
{
    return m_allowErrorCode;
}

void RateControl::start()
{
    m_totalSampleCount = 0;
    m_startTime.start();
}

void RateControl::restart()
{
    start();
}

int RateControl::addSample(int sampleCount)
{
    if(m_sampling == 0)
    {
        return -1;
    }

    int timeInterval = 0;
    m_totalSampleCount += sampleCount;
    double actualSpanTime = static_cast<quint64>(totalSpan()) / 1e3;  //(double)m_watch.ElapsedMilliseconds / 1e3;
    double expectSampleCount = m_sampling * actualSpanTime;
    //实际添加样点数超出预期范围，直接
    if (m_totalSampleCount - expectSampleCount > m_allowErrorCode)
    {
        int addVal = static_cast<int>((m_totalSampleCount - expectSampleCount) * 1e3 / m_sampling);
        timeInterval += addVal;
    }
    else
    {
        timeInterval = 0;
    }

    if (actualSpanTime >= m_resetInteval)
    {
        restart(); // 达到时间门限，自动重设，保证微观上的时间误差
    }
    return timeInterval;
}

qint64 RateControl::totalSpan() const
{
    return m_startTime.elapsed();
}

int RateControl::sampling() const
{
    return m_sampling;
}

void RateControl::setSampling(int sampling)
{
    m_sampling = sampling;
    m_allowErrorCode = sampling / 50; // 误差数 ，默认50ms的数据量。
    m_totalSampleCount = 0;
}
